package com.hongbao.game.service;

import org.springframework.stereotype.Component;

@Component
public class PessimisticLock_DB {

    //table PessimisticLock_DB
    //锁name  线程guid+threadId  ，重入的次数
    public boolean getLock(String name)  {
        //自旋的方式
        boolean result = false;
        String threadName = Thread.currentThread().getName();
        //判断锁是否存在
        //select name,threadName,value from PessimisticLock_DB where name = ${name}
        //没有记录
            //insert into PessimisticLock_DB value(name,threadName,1)
        //有记录 锁存在
            // 线程ID相同 //update PessimisticLock_DB set value = value+1 where name=${name) and threadName=${threadName}
            // 线程ID相同 // 等待  //自旋的方式

        while (result) {
            //update  PessimisticLock_DB set state=1,currentThreadName = ${threadName} where (state=0 and name=${name}) or
            // (state=1 and name=${name} and currentThreadName = ${threadName})
            //第一次加锁
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public boolean releaseLock(String name){
        //
        String threadName = Thread.currentThread().getName();
        ////select name,threadName,value from PessimisticLock_DB where name = ${name} and threadName=${threadName
        //如果 有记录
             //value >1  //update PessimisticLock_DB set value=value-1 where  threadName=${threadName} and name=${name}
            // value <=1 //delect From PessimisticLock_DB where name = ${name} and threadName=${threadName}
        return true;
    }
}
